package com.yycx.module.bus.provider.handler.haiying.tasktodo.askamount;

import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.BusHyorderReturnService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 认款审批结束监听器
 *
 * @author zyf
 */
@Component
public class HyReturnAmountProcessEndListener implements ExecutionListener {

    @Resource
    private BusPaymentService paymentService;


    @Resource
    private BusSalemanBalanceService salemanBalanceService;

    @Resource
    private BusHyorderReturnService hyorderReturnService;

    @Resource
    private BusDepositService depositService;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String businessKey = delegateExecution.getVariable("businessKey", String.class);
        BusPayment payment = paymentService.getById(businessKey);
        //更新为已审批状态
        paymentService.updatePaymentState(payment.getPaymentId(), CommonConstants.INT_2);
        String amountType = payment.getAmountType();
        if (amountType.equals(AmountTypeEnum.CustomRefund.getCode())) {
            //更新明细表中回款信息
            hyorderReturnService.updateReturnInfo(payment);
            //添加回款明细
            hyorderReturnService.insertToPaymentOrderList(payment);
        }
        //资保金认款
        if (amountType.equals(AmountTypeEnum.CustomBond.getCode())) {
            //添加或者更新资保金余额
            salemanBalanceService.saveSalManBalance(payment);
            //质押金金额
            BigDecimal depositAmount = payment.getReturnAmount();
            if (FlymeUtils.gtzero(depositAmount)) {
                //添加押金收款记录
                depositService.addDeposit(payment);
            }
        }
        if (amountType.equals(AmountTypeEnum.DepositAmount.getCode())) {
            //更新认款状态
            depositService.updateDepositState(payment.getPaymentId(), CommonConstants.INT_1);
        }
    }

}
